import React, { CSSProperties } from 'react'
import { DriveFileRenameOutline } from '@material-ui/icons'
import { Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle,TextField,Button } from '@material-ui/core'
import {inject,observer} from 'mobx-react'
import UserStore from '../../../store/modules/userStore'
import Message from '../../../components/Message/Message'
import { cgName,CgAns } from '../../../api/user'

const ChangeNameStyle: CSSProperties = {
    backgroundColor: '#fff',
    boxShadow: '1px 2px 25px 0px rgb(0 0 0 / 10%)',
    borderRadius: '15px',
    margin: '2vh 4vw',
    padding: '1.5vh 3vw',
    display: 'flex',
    alignItems: 'center'
}
interface IProps {
    userStore?: UserStore 
}
const ChangeName = (props: IProps) => {
    const nickNameReg = /^.{2,8}$/
    const [open,setOpen] = React.useState<boolean>(false)
    const [newName,setNewName] = React.useState<string>('')
    const handleUpdate = () => {
        if(nickNameReg.test(newName)){
            cgName(newName)
                .then(res => {
                    const {code,msg} = res as unknown as CgAns
                    if(code === 200){
                        props.userStore?.getUserInfo()
                        setNewName('')
                        setOpen(false)
                        Message('success',msg)
                    }else{
                        Message('error',msg)
                    }
                })
                .catch(err => {
                    console.log(err);
                })
        }else{
            setNewName('')
            Message('error','用户名格式错误')
        }
    }
    return (
        <>
            <div style={ChangeNameStyle} onClick={() => {setOpen(true)}}>
                <DriveFileRenameOutline />
                <span style={{ marginLeft: '4vw', fontSize: '13px' }}>修改用户名</span>
            </div>
            <Dialog open={open}>
                <DialogTitle>修改用户名</DialogTitle>
                <DialogContent>
                    <DialogContentText>
                        请填写您即将更改的用户名：2-8位任意字符
                    </DialogContentText>
                    <TextField  autoFocus id="newName" label="新用户名" type="text"  fullWidth variant="standard" value={newName} color='secondary' onChange={(e) => {
                        setNewName(e.target.value)
                    }}/>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleUpdate} color='secondary'>更改</Button>
                    <Button onClick={() => {setOpen(false)}} color='secondary'>取消</Button>
                </DialogActions>
            </Dialog>
        </>
    )
}

export default inject('userStore')(observer(ChangeName))